package cn.turboinfo.fuyang.api.provider.admin.impl.permission;

import cn.turboinfo.fuyang.api.domain.admin.service.permission.PermissionService;
import cn.turboinfo.fuyang.api.entity.admin.exception.user.PermissionException;
import cn.turboinfo.fuyang.api.entity.admin.pojo.permission.Permission;
import cn.turboinfo.fuyang.api.provider.admin.repository.database.permission.PermissionDAO;
import cn.turboinfo.fuyang.api.provider.admin.repository.database.permission.PermissionPO;
import cn.turboinfo.fuyang.api.provider.common.repository.database.role.RolePermissionDAO;
import cn.turboinfo.fuyang.api.provider.common.repository.database.role.RolePermissionPO;
import lombok.RequiredArgsConstructor;
import net.sunshow.toolkit.core.qbean.helper.service.impl.DefaultQServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class PermissionServiceImpl extends DefaultQServiceImpl<Permission, Long, PermissionPO, PermissionDAO> implements PermissionService {

    private final RolePermissionDAO rolePermissionDAO;

    @Override
    public Optional<Permission> getByResource(String resource) {
        return dao.findByResource(resource).map(this::convertQBean);
    }

    @Override
    public List<Permission> findByResourceIn(Collection<String> resourceCollection) {
        return dao.findByResourceIn(resourceCollection).stream().map(this::convertQBean).collect(Collectors.toList());
    }

    @Override
    public List<Permission> findByParentId(Long parentId) {
        return dao.findByParentIdOrderBySortValueAscIdAsc(parentId).stream().map(this::convertQBean).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        PermissionPO po = deleteAndReturn(id);

        // 删除已分配给角色的权限记录
        List<RolePermissionPO> rolePermissionPOList = rolePermissionDAO.findByPermissionId(po.getId());
        rolePermissionDAO.deleteAll(rolePermissionPOList);
    }

    @Override
    protected Supplier<? extends RuntimeException> getExceptionSupplier(String message,
                                                                        Throwable cause) {
        return () -> new PermissionException(message, cause);
    }

}
